package com.shenfa.action.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.shenfa.dao.xml.MakeXmlDao;
import com.shenfa.util.SysRun;


public class UploadAction extends ActionSupport implements ServletResponseAware {

	@Autowired
	private MakeXmlDao makeXmlDao;
	private static final long serialVersionUID = 1L;
	private File file;
	private File oldFile;
	private String fileFileName;//文件名
	private String mag;	//返回消息
	private String type;//存储类型(模板，素材)
	private String id;	//自定义存储目录名
	private HttpServletResponse response;
	private FileOutputStream fos;
	private FileInputStream fis;
	private String basepath;//基础路径
	private String temp;
	private static Logger log=Logger.getLogger(UploadAction.class);
	public String execute() {
		log.debug("type="+type+",id="+id+",filename="+fileFileName);
		basepath=makeXmlDao.getConfig().get("BASEPATH");
		//根据上传文件的类型选择保存的目录
		//如果是模板文件上传
		if ("template".equals(type)) {			
			String str = fileFileName.substring(fileFileName.lastIndexOf("."));
			if(!".wfd".equalsIgnoreCase(str)&&!".job".equalsIgnoreCase(str)){
				fileFileName = ""+System.currentTimeMillis()+fileFileName.substring(fileFileName.lastIndexOf("."));
			}
			temp = basepath+id + "/";
		}//如果是素材文件上传
		else if("fodder".equals(type)){
			temp = basepath+"PIC/";
		}//如果是预印纸文件上传
		else if("paper".equals(type)){
			temp = basepath+id;
			int end = temp.lastIndexOf("/");
			temp = temp.substring(0, end);
		}
		//判断文件目录是否存在
		oldFile=new File(temp);
		if(!oldFile.exists()){
			oldFile.mkdirs();
			//如果是模板的创建目录事件，则调用linux命令，修改目录的权限
			if("template".equals(type)){
				try {
					SysRun.chmod(makeXmlDao.getConfig().get("UPLOAD_CHMOD"),temp);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		//如果是预印纸文件
		if("paper".equals(type)){
			oldFile = new File(basepath+id);
		}//如果是素材文件
		else if("fodder".equals(type)){
			//修改文件的名称
			String p=fileFileName.substring(fileFileName.lastIndexOf("."));
			temp=temp+System.currentTimeMillis()+p;
			oldFile = new File(temp);
		}
		else{
			oldFile = new File(temp + fileFileName);
		}
		//判断上传的文件是否存在
		if (null == file || !file.exists()) {
			mag = "notfile";
			this.toReturn(mag);
			return null;
		}
		// 判断文件是否存在
		else if (oldFile.exists()){
			//如果为预印纸则先删除
			if("paper".equals(type)){
				oldFile.delete();
			}
			else if ("template".equals(type)) {
				
			}
			//如果不为覆盖操作则返回错误信息
			else{
				mag = "exists";
				this.toReturn(mag);
				return null;
			}
		} 		
		//写入文件
		if(this.beginWrite()){
			mag = "success";
		}else{
			mag="error";
		}
		//写入成功后的处理
		if("success".equals(mag)){
			if("fodder".equals(type)){
				mag=temp;
			}
			else if("template".equals(type)){
				mag+= "|"+temp+fileFileName;
			}else if("paper".equals(type)){
				mag+=basepath+id;
			}
		}
		this.toReturn(mag);
		return null;
	}
	/**
	 * 上传文件写入处理
	 * @return
	 */
	private boolean beginWrite(){
		try {
			log.debug("type="+type+",filepath="+file.getPath());
			oldFile.createNewFile();// 创建文件实体
			fos = new FileOutputStream(oldFile);
			fis = new FileInputStream(file);
			// 将上传文件的内容写入服务器
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return false;
		}finally{
			try {
				if(null!=fis)fis.close();
				if(null!=fos)fos.close();
			} catch (IOException e) {
				e.printStackTrace();
				log.error(e.getMessage());
				return false;
			}
		}
		return true;
	}
	/**
	 *返回消息处理
	 * @param msg
	 */
	private void toReturn(String msg){
		try {
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(msg);
			response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
	
	public void setFile(File file) {
		this.file = file;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getMag() {
		return mag;
	}

	public void setServletResponse(HttpServletResponse arg0) {
		response = arg0;
	}

	public void setType(String type) {
		this.type = type;
	}

	public void setId(String id) {
		this.id = id;
	}

	
}
